package com.beadwallet.alarm.config;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.enums.FieldStrategy;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.beadwallet.alarm.base.datasource.ChooseDataSource;
import com.beadwallet.alarm.base.datasource.DataSourceConfiguration;
import com.beadwallet.common.utils.PropertiesUtil;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.ObjectUtils;

/**
 * Created by jack-cooper on 2017/1/16.
 */

@Configuration
@ConditionalOnClass({EnableTransactionManagement.class})
@Import({DataSourceConfiguration.class})
@MapperScan("com.beadwallet.alarm.mapper")
public class MybatisPlusConfig {

    private Logger logger = LogManager.getLogger(MybatisPlusConfig.class);

    @Autowired
    private Interceptor[] interceptors;
    @Autowired
    private ChooseDataSource chooseDataSource;
//    @Autowired
//    private ResourceLoader resourceLoader = new DefaultResourceLoader();
//    @Autowired(required = false)
//    private DatabaseIdProvider databaseIdProvider;
    @Autowired(required = false)
    private PropertiesBean propertiesBean;


    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /***
     *  配置Mybatis SqlSessionFatory
     * @return
     */
    @Bean("sqlSessionFactory")
    @ConfigurationProperties(prefix = "mybatis")
    public MybatisSqlSessionFactoryBean getMyBatisSqlSessionfactoryBean() {
        PropertiesUtil.setProperties(propertiesBean.getPropertiesBean());
//        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
        mybatisPlus.setDataSource(chooseDataSource);
        mybatisPlus.setVfs(SpringBootVFS.class);
        if (!ObjectUtils.isEmpty(this.interceptors)) {
            mybatisPlus.setPlugins(this.interceptors);
        }
        // MP 全局配置，更多内容进入类看注释
        GlobalConfiguration globalConfig = new GlobalConfiguration();
        globalConfig.setDbType(DBType.MYSQL.name());
        // ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
        globalConfig.setIdType(0);
        globalConfig.setFieldStrategy(FieldStrategy.NOT_EMPTY.getKey());
        mybatisPlus.setGlobalConfig(globalConfig);
        MybatisConfiguration mc = new MybatisConfiguration();
        mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        //mapUnderscoreToCamelCase：是否启用下划线与驼峰式命名规则的映射（如first_name => firstName）
        mc.setMapUnderscoreToCamelCase(false);
        mybatisPlus.setConfiguration(mc);
        return mybatisPlus;
    }

    /**
     * 自定义事务
     * MyBatis自动参与到spring事务管理中，无需额外配置，只要org.mybatis.spring.SqlSessionFactoryBean引用的数据源与DataSourceTransactionManager引用的数据源一致即可，否则事务管理会不起作用。
     *
     * @return
     */
    @Bean(name = "transactionManager")
    public org.springframework.jdbc.datasource.DataSourceTransactionManager transactionManagers() {
        logger.info("-------------------- transactionManager init ---------------------");
        return new org.springframework.jdbc.datasource.DataSourceTransactionManager(chooseDataSource);
    }

}
